#include <git2.h>
#include <stdio.h>
#include <string.h>

int main() {
	git_libgit2_init();
	char *repo_path = "test_repos";
	git_repository *repo;
	int i;
	int error = git_repository_open(&repo ,repo_path);
	if(error<0) {
		printf("git_repository_open failed, error msg:%s\n", giterr_last()->message);
	}
	printf("open ok\n");

	//head
	git_reference *head;
	git_repository_head(&head, repo);
	printf("repository head: %s\n", git_reference_name(head));
	if(git_reference_is_branch(head) == 1) {
		printf("head reference %s is branch\n", git_reference_name(head));
	} else {
		printf("head reference %s is'nt branch\n", git_reference_name(head));
	}

	const git_oid *oid = git_reference_target(head);
	char out[GIT_OID_HEXSZ+1];
	git_oid_fmt(out, oid);
	printf("head reference target oid:%s\n", out);

	git_commit *commit;
	error = git_commit_lookup(&commit, repo, oid);
	if(error !=0) {
		printf("git_commit_lookup failed, error code:%d, code message:%s\n", error, giterr_last()->message);
		return -1;
	}

	const git_signature *author = git_commit_author(commit);
	const git_signature *cmtter = git_commit_committer(commit);
	const char *message = git_commit_message(commit);
	time_t time = git_commit_time(commit);
	printf("author:(%s, %s)\ncommitter:(%s, %s)\ncommit message:%s\ncommit time:%s\n", author->name, author->email, cmtter->name, cmtter->email, message, ctime(&time));
	printf("commit summary:\n%s\n", git_commit_summary(commit));
	printf("commit message encoding:%s\n", git_commit_message_encoding(commit));

	int	parents  = git_commit_parentcount(commit);
	git_commit *parent;
  for (i = 0;i < parents; ++i) {
    git_commit_parent(&parent, commit, i);
    git_oid_fmt(out, git_commit_id(parent));
    printf("Parent: %s\n", out);
    git_commit_free(parent);
  }

	const git_oid *tree_id = git_commit_tree_id(commit);
	bzero(out, GIT_OID_HEXSZ+1);
	git_oid_fmt(out, tree_id);
	printf("commit tree id:%s\n", out);

	git_commit_free(commit);
	git_reference_free(head);
	git_repository_free(repo);
	return 0;
}
